import eventBus  from "./EventBus"

const WS_PARSE_ERROR = 'parse_error'
const WS_SERVER_ERROR = 'server_error'

class Socket{
  
  static install (Vue) {
    if (Socket.install.isInstall) {
      return true
    }
    // 赋值给全局变量，方便别的方法访问
    Socket._Vue = Vue
    Socket.install.isInstall = true

    // 通过混入的方式可以拿到vue的根实例
    Socket._Vue.mixin({
      // 所有的vue实例都会执行beforeCreate，所以我们要保证旨在根实例创建的时候，将router实例赋值给Vue的原型，保证所有的vue组件都可以访问到 $router
      beforeCreate () {
        if (this.$options.socketer) {
          Socket._Vue.prototype.$socketer = this.$options.socketer
        }
      }
    })
  }

  //创建监听
  static listen(host,port,id){
    //一个页面只允许创建一次监听
    if(Socket.listen.isListen){
      return true
    }
    Socket.listen.isListen = true
    return new Socket(host,port,id)
  }

  constructor(host,port,id){
    this.host = host
    this.port = port
    this.id = id

    this.addr = `ws://${host}:${port}`
    if(id){
      this.addr += id
    }

    this.socket = new WebSocket(this.addr)
    
    this.onMessage()
    this.onOther()
  }

   onMessage(){
    this.socket.addEventListener('message',(event)=>{
      try{
        let parseRes = JSON.parse(event.data)
        if(parseRes.err_code === undefined || parseRes.event === undefined){
          eventBus.$emit(WS_PARSE_ERROR,'ws:未指定事件类型')
          return false
        }
        console.log(parseRes.event)
        eventBus.$emit(parseRes.event,parseRes)
      }catch(error){
        eventBus.$emit(WS_PARSE_ERROR,'ws:数据解析错误')
      }
    }) 
  }

  onOther(){
    let arr = ['open','close','error']
    arr.forEach((eventName)=>{
      this.socket.addEventListener(eventName,(event)=>{
        eventBus.$emit(eventName,event)
     })
    })
  }

}

export {Socket,eventBus}
